#!/usr/local/bin/python3
# _*_ coding:utf-8 _*_

import Config
import requests
import json

class DingDing():
    def __init__(self):
        pass

    def send(self,item):
        if item is None:
            print("invalid item for dingding notify")
            return False
        for ding in Config.DINGDING:
            s = """#丁香医生播报#\n【{}】\n\n{}\n\n信息来源：{}""".format(item.get("title"),item.get("summary"),item.get("infoSource"))
            ding["template"]["text"]["content"] = s
            res = requests.post(url=ding["url"],headers=ding["header"],data=json.dumps(ding["template"]))
            if res.status_code != 200:
                print("钉钉发送出错,返回：")
                print(res.json())
                return False
        #print("钉钉通知发送成功")
        return True

class ServerChan():
    def __init__(self):
        self.url = "https://sc.ftqq.com/{}.send?text={}&desp={}"
        self.desp = """%23%23%23+{}%0D%0A%0D%0A%23%23%23%23{}"""

    def check_need_send(self,title,keywords):
        if len(keywords) == 0:
            return True
        for word in keywords:
            if title.find(word) > -1:
                return True
        return False

    def send(self,item):
        if item is None:
            print("invalid item for ServerChan")
            return False
        for sc in Config.SERVER_CHAN:
            if sc["is_filter"] and not self.check_need_send(item.get("title"),sc["keywords"]):
                continue
            title = "{}".format(item.get("infoSource"))
            content = self.desp.format(item.get("title"),item.get("summary"))
            url = self.url.format(sc["token"],title,content)
            res = requests.get(url)
            if res.status_code != 200 or res.json().get("errno") != 0:
                print("发送serverChan出错，返回：")
                print(res.json())
                return False
        #print("Server酱通知成功")
        return True
if __name__ == "__main__":
    s = ServerChan()
    print(ServerChan.check_need_send("甘肃发现好VBeve",["广东","甘肃"]))

